package io.hellsinger.navigation.screen

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.FrameLayout.LayoutParams.MATCH_PARENT
import androidx.viewpager2.widget.ViewPager2
import io.hellsinger.navigation.screen.HostScreenControllerAdapter.ScreenControllerProvider

abstract class HostScreenController<Args> :
    ScreenController<Args>(),
    ScreenControllerProvider {
    protected val adapter = HostScreenControllerAdapter(this)
    protected var pager: ViewPager2? = null

    private var currentPosition: Int = 0

    private val current: ScreenController<*>?
        get() {
            val selected = pager?.currentItem ?: return null
            return adapter.getController(selected)
        }

    override fun onCreateViewImpl(context: Context): View {
        pager =
            ViewPager2(context).apply {
                layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                adapter = this@HostScreenController.adapter
            }

        return pager!!
    }

    protected open fun wrapPrefix(prefix: String): String = prefix + "host_screen_controller_"

    override fun onSaveImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean {
        var saved = 0
        for (i in 0 until adapter.itemCount) {
            if (adapter.getController(i).onSave(buffer, prefix)) saved++
        }
        return saved > 0
    }

    override fun onRestoreImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean {
        var restored = 0
        for (i in 0 until adapter.itemCount) {
            if (adapter.getController(i).onRestore(buffer, wrapPrefix(prefix))) restored++
        }
        return restored > 0
    }

    override fun onActivityResultImpl(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
    ): Boolean =
        current?.onActivityResult(
            requestCode,
            resultCode,
            data,
        ) ?: super.onActivityResultImpl(requestCode, resultCode, data)

    override fun onBackActivatedImpl(): Boolean = current?.onBackActivated() ?: false
}
